package com.definesys.smecrailtransit;

import android.databinding.DataBindingUtil;
import android.os.Handler;
import android.support.v4.app.Fragment;

import android.os.Bundle;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.definesys.smecrailtransit.SmecManager.SmecDialog.SmecDialog;
import com.definesys.smecrailtransit.SmecManager.SmecSession.SmecSession;
import com.definesys.smecrailtransit.api.SmecRailConstant;
import com.definesys.smecrailtransit.base.SmecBaseActivity;


import com.definesys.smecrailtransit.databinding.ActivityMainBinding;
import com.definesys.smecrailtransit.module.Login.LoginActivity;
import com.definesys.smecrailtransit.module.MonthForm.MonthFormFragment;
import com.definesys.smecrailtransit.module.RealStatus.RealStatusFragment;
import com.definesys.smecrailtransit.module.RealTime.RealTimeFragment;
import com.definesys.smecrailtransit.module.SiteDetails.SiteDetailsFragment;
import com.definesys.smecrailtransit.module.TotalTime.TotalTimeFragment;
import com.definesys.smecrailtransit.receiver.JPushReceiver;
import com.definesys.smecrailtransit.widget.TopBarLayout;

import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.github.mzule.activityrouter.annotation.Router;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;


import java.util.ArrayList;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

import static com.definesys.smecrailtransit.module.Navigation.NavigationAdapter.NavigationAdapter.NAVIGATION;
import static com.definesys.smecrailtransit.receiver.JPushReceiver.ACTIVITY_OPENDED;

@Router("MainActivity")
public class MainActivity extends SmecBaseActivity {

    public static final String JPUSH_REFRESH="JPUSH_REFRESH";
    public static final String WAY_TO_FRAGMNET="WAY_TO_FRAGMNET";
    private ActivityMainBinding activityMainBinding;
    private ArrayList<Fragment> fragmentArrayList;
    public int fragmentChange=0;
    private TopBarLayout topBarLayout;
    private NormalDialog normalDialog;
    private DrawerLayout drawerLayout;

    private Handler mHandler=new Handler(){};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityMainBinding=DataBindingUtil.setContentView(this,R.layout.activity_main);
        activityMainBinding.setCurrentItem(fragmentChange);
        _initView();
        _getDataFromIntent();
    }

    @Override
    public Object getPresenter() {
        return null;
    }

    /**
     * 从Intent中获取数据
     */
    private void _getDataFromIntent(){
        String position=getIntent().getStringExtra(NAVIGATION);
        if(position !=null && !position.equals("")){
            int navPosition=Integer.parseInt(position);
            _changeFragment(navPosition);
            return;
        }
        String type=getIntent().getStringExtra("JPUSH_TYPE");
        if(type!=null){
            if(type.equals(JPushReceiver.JPUSH_TYPE_REAL)){
                fragmentChange=0;
            }
            if(type.equals(JPushReceiver.JPUSH_TYPE_REPORT)){
                fragmentChange=1;
            }
            _changeFragment(fragmentChange);
        }
    }

    /**
     * 侧滑切换Fragment
     * @param view
     */
    public void switchFragment(View view){
        switch (view.getId()){
            case R.id.real_msg:
                fragmentChange=0;
                break;
            case R.id.site_details:
                fragmentChange=1;
                break;
            case R.id.real_status:
                fragmentChange=2;
                break;
            case R.id.fault_st:
                fragmentChange=3;
                break;
            case R.id.operator_status:
                fragmentChange=4;
                break;
            case R.id.login_out:
                _getDialog();
                normalDialog.show();
                return;
        }
        drawerLayout.closeDrawer(GravityCompat.END);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                _changeFragment(fragmentChange);
            }
        },200);
    }

    /**
     * 切换Fragment
     * @param navPosition
     */
    private void _changeFragment(int navPosition){
        fragmentChange=navPosition;
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                topBarLayout.getTvTextTitle().setText(getString(SmecRailConstant.getNavigationTitle().get(fragmentChange)));
                mRxBus.post(WAY_TO_FRAGMNET,fragmentChange+"");
            }
        },200);
        activityMainBinding.pager.setCurrentItem(fragmentChange,false);
        activityMainBinding.invalidateAll();
    }

    /**
     * 初始化数据
     */
    private void _initView(){
        fragmentArrayList=new ArrayList<>();
        fragmentArrayList.add(RealTimeFragment.newInstance());
        fragmentArrayList.add(SiteDetailsFragment.newInstance());
        fragmentArrayList.add(RealStatusFragment.newInstance());
        fragmentArrayList.add(MonthFormFragment.newInstance());
        fragmentArrayList.add(TotalTimeFragment.newInstance());
        activityMainBinding.navi.setUsername(SmecSession.getSmecUser().getUserName() + "  您好");
        activityMainBinding.pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {

            public int getCount() {
                return fragmentArrayList.size();
            }

            public Fragment getItem(int position) {
                return fragmentArrayList.get(position);
            }
        });
        activityMainBinding.pager.setOffscreenPageLimit(fragmentArrayList.size()-1);

        Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                _setTopNaviMsg();
            }
        }).subscribeOn(Schedulers.io()).
                unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Object>() {
                    @Override
                    public void call(Object o) {
                        Log.e("当前时间：",System.currentTimeMillis()+"");
                    }
                });
    }

    /**
     * 设置导航栏侧滑信息
     */
    private void _setTopNaviMsg(){
        topBarLayout=activityMainBinding.topBarLayout;
        drawerLayout=activityMainBinding.drawerLayout;
        activityMainBinding.topBarLayout.setTopBarListener(new TopBarLayout.TopBarListener() {
            @Override
            public void setOnLeftClickListener() {
                appManager.finishActivity();
            }

            @Override
            public void setOnRight1ClickListener() {

            }
            @Override
            public void setOnRight2ClickListener() {
                showOrHideRecycler();
            }
        });
        drawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(View drawerView) {
                activityMainBinding.getRoot().setClickable(false);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                activityMainBinding.getRoot().setClickable(true);
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });
        TextView nvaiView=topBarLayout.gettvTextRightSecond();
        ViewGroup.LayoutParams layoutParams=nvaiView.getLayoutParams();
        layoutParams.height=80;
        layoutParams.width=80;
        nvaiView.setBackground(getResources().getDrawable(R.drawable.ele_navi));
    }

    /**
     * 实例化dialog
     * @return
     */
    private NormalDialog _getDialog(){
        if(normalDialog == null){
            normalDialog= SmecDialog.getInstance(this,"退出登录吗?");

            normalDialog.setOnBtnClickL(
                    new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            normalDialog.dismiss();
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    finish();
                                    mRxBus.post(LoginActivity.LOGIN_SEWITCH,new Object());
                                }
                            },300);
                        }
                    });
        }
        return normalDialog;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(ACTIVITY_OPENDED)
            }
    )
    public void openedActivity(String funName){

        if(funName !=null && !funName.equals("")){
            if(funName.equals(JPushReceiver.JPUSH_TYPE_REAL)){
                if(fragmentChange == 0){
                    mRxBus.post(JPUSH_REFRESH,new Object());
                    return;
                }
                fragmentChange=0;
            } else if(funName.equals(JPushReceiver.JPUSH_TYPE_REPORT)){
                if(fragmentChange == 1){
                    return;
                }
                fragmentChange=1;
            }
            Log.e("ssss","ssssseqweqe");
            _changeFragment(fragmentChange);
            Log.e("ssss","qwerqwerqw");
        }
    }


    public void showOrHideRecycler() {
        if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
            drawerLayout.closeDrawer(GravityCompat.END);
        } else {
            drawerLayout.openDrawer(GravityCompat.END);
        }
    }

}
